package com.example.alarmclock;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Toast;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity implements TimePicker.OnTimeChangedListener {
    public static final String ACTION_ALARM = "com.book.action.set_alarm";
    private AlarmManager am = null;
    private TimePicker tpTime;
    private int hourOfDay =  0;
    private int minute =  0;
    String text;
    private Calendar calendar = Calendar.getInstance();
    PendingIntent sender;
    private AlarmReceiver alarmReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tpTime = (TimePicker)findViewById(R.id.tp_time);
        tpTime.setIs24HourView(true);
        tpTime.setOnTimeChangedListener(this);
        Intent i = new Intent();
        i.setAction(ACTION_ALARM);

        sender = PendingIntent.getBroadcast(
                MainActivity.this,0,i,PendingIntent.FLAG_UPDATE_CURRENT
        );
        hourOfDay = tpTime.getCurrentHour();
        minute = tpTime.getCurrentMinute();
        registerBroadCastReceiver();

    }

    public void clickSet(View view) {
        am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),sender);
        Toast.makeText(MainActivity.this,"设置成功",Toast.LENGTH_LONG).show();
    }

    @Override
    public void onTimeChanged(TimePicker view, int h, int m) {
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY,h);
        calendar.set(Calendar.MINUTE,m);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND,0);
        hourOfDay = h;
        minute = m;
    }

    private void registerBroadCastReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_ALARM);
        alarmReceiver = new AlarmReceiver();
        registerReceiver(alarmReceiver,filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(alarmReceiver);
    }
}
